package com.hlpedu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.nio.charset.Charset;
import java.util.List;

/*SpringMvcConfig配置类代替的是spring-mvc.xml文件*/
@Configuration//标注当前类是Java配置类
@ComponentScan("com.hlpedu.controller")//指定扫描包
@EnableWebMvc//开启注解支持，响应json格式注解时必须使用此注解
public class SpringMvcConfig implements WebMvcConfigurer {
    //配置视图解析器

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/pages/",".jsp");
    }

    //配置字符集过滤器，通过@EnableWebMvc配置的时候起作用
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter httpMessageConverter:converters){
            if (StringHttpMessageConverter.class.isAssignableFrom(httpMessageConverter.getClass())){
                ((StringHttpMessageConverter) httpMessageConverter).
                        setDefaultCharset(Charset.forName("UTF-8"));

            }

        }
    }

    @Bean
    public HandlerMapping handlerMapping(){
        System.out.println("HandlerMapping创建了。。。");
        return new RequestMappingHandlerMapping();
    }
    @Bean
    public HandlerAdapter handlerAdapter(){
        System.out.println("HandlerAdapter创建了。。。");
        return new RequestMappingHandlerAdapter();
    }
}
